const connection = require('../app/batabase');

class CommentService {
    async createService (user_id, content, moment_id) {
      try {
        const statement = `INSERT INTO comment (content, moment_id, user_id) VALUE (?, ?, ?);`;
        const [result] = await connection.execute(statement, [content, moment_id, user_id]);
        // console.log(result);     //拿到的是一个数组，数组的第0位就是插入成功后返回的信息，使用数组结构拿到第0位的数据，是一个对象
        return result; 
      } catch (err) {
        console.log(err);
      }
    }

    async replyService (moment_id, content, user_id ,comment_id) {
      try {
        const statement = `INSERT INTO comment (content, moment_id, user_id, comment_id) VALUE (?, ?, ?, ?);`;
        const [result] = await connection.execute(statement, [content, moment_id, user_id, comment_id]);
        return result;  
      } catch (err) {
        console.log(err);
      }
    }

    async updateService (commentId, content) {
      try {
        const statement = `UPDATE comment SET content = ? WHERE id = ?;`;
        const [result] = await connection.execute(statement, [content, commentId]);
        return result; 
      } catch (err) {
        console.log(err);
      }
    }

    async removeService (commentId) {
      try {
        const statement = `DELETE FROM comment WHERE id = ?`;
        const [result] = await connection.execute(statement, [commentId]);
        return result;
      } catch (err) {
        console.log(err);
      }
    }

       //单独获取指定的评论数据(根据comment表中的moment_id字段)
    async getCommentsByMomentId (momentId) {
      try {
        const statement = `
        SELECT
        m.id, m.content, m.comment_id commentId, m.createAt createTime,
          JSON_OBJECT('id', u.id, 'name', u.name) user
        FROM comment m
        LEFT JOIN user u ON m.user_id = u.id
        WHERE moment_id = ?;
        `;
        const [result] = await connection.execute(statement, [momentId]);
        // console.log(result);s
        return result;
      } catch (err) {
        console.log(err);
      }
    }
}


module.exports = new CommentService();